// BilibiliQRCodePoller.cpp
#include "BilibiliQRCodePoller.h"
#include <QNetworkRequest>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>
#include <QUrl>
#include <QUrlQuery>
#include <QDebug>
#include <QTimer>

BilibiliQRCodePoller::BilibiliQRCodePoller(QObject *parent)
    : QObject(parent)
    , m_networkManager(new QNetworkAccessManager(this))
{
    connect(m_networkManager, &QNetworkAccessManager::finished,
            this, &BilibiliQRCodePoller::onReplyFinished);
}

void BilibiliQRCodePoller::sendRequest(const QString &qrcodeKey)
{
    QString baseUrl = "https://passport.bilibili.com/x/passport-login/web/qrcode/poll";

    // 构建URL和查询参数
    QUrl url(baseUrl);
    QUrlQuery query;
    query.addQueryItem("qrcode_key", qrcodeKey);
    url.setQuery(query);

    // 创建请求
    QNetworkRequest request(url);

    // // 设置请求头
    // request.setRawHeader("User-Agent",
    //                      "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
    // request.setRawHeader("Accept", "application/json, text/plain, */*");
    // request.setRawHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
    // request.setRawHeader("Referer", "https://passport.bilibili.com/");

    // 发送GET请求
    QNetworkReply *reply = m_networkManager->get(request);

    // 设置超时
    QTimer::singleShot(10000, reply, &QNetworkReply::abort);
}

QJsonObject BilibiliQRCodePoller::processResponseData(const QByteArray &responseData)
{
    QJsonObject result;

    // 解析JSON
    QJsonParseError parseError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(responseData, &parseError);

    if (parseError.error != QJsonParseError::NoError) {
        qDebug() << "JSON解析错误:" << parseError.errorString();
        result["error"] = "JSON解析失败";
        return result;
    }

    QJsonObject jsonObj = jsonDoc.object();

    // 提取主要字段
    result["code"] = jsonObj["code"].toInt();
    result["message"] = jsonObj["message"].toString();
    result["ttl"] = jsonObj["ttl"].toInt();

    // 处理data字段
    if (jsonObj.contains("data")) {
        QJsonObject dataObj = jsonObj["data"].toObject();

        QJsonObject processedData;
        processedData["url"] = dataObj["url"].toString();
        processedData["refresh_token"] = dataObj["refresh_token"].toString();
        processedData["timestamp"] = dataObj["timestamp"].toInt();
        processedData["code"] = dataObj["code"].toInt();
        processedData["message"] = dataObj["message"].toString();

        result["data"] = processedData;
    }

    return result;
}

void BilibiliQRCodePoller::onReplyFinished(QNetworkReply *reply)
{
    reply->deleteLater();

    if (reply->error() != QNetworkReply::NoError) {
        qDebug() << "网络请求错误:" << reply->errorString();
        return;
    }

    // 读取响应数据
    QByteArray responseData = reply->readAll();

    // 调用数据处理方法
    QJsonObject processedJson = processResponseData(responseData);

    // 处理结果
    if (processedJson.contains("error")) {
        qDebug() << "处理错误:" << processedJson["error"].toString();
        return;
    }

    // 输出处理后的JSON
    qDebug() << "处理后的JSON:";
    qDebug() << "  code:" << processedJson["code"].toInt();
    qDebug() << "  message:" << processedJson["message"].toString();
    qDebug() << "  ttl:" << processedJson["ttl"].toInt();

    if (processedJson.contains("data")) {
        QJsonObject dataObj = processedJson["data"].toObject();
        qDebug() << "  data:";
        qDebug() << "    url:" << dataObj["url"].toString();
        qDebug() << "    refresh_token:" << dataObj["refresh_token"].toString();
        qDebug() << "    timestamp:" << dataObj["timestamp"].toInt();
        qDebug() << "    code:" << dataObj["code"].toInt();
        qDebug() << "    message:" << dataObj["message"].toString();

        // 根据状态码处理
        int statusCode = dataObj["code"].toInt();
        switch (statusCode) {
        case 86038:
            qDebug() << "状态: 二维码已失效";
            break;
        case 86101:
            qDebug() << "状态: 未扫描二维码";
            break;
        case 86090:
            qDebug() << "状态: 已扫描二维码，等待确认";
            break;
        case 0:
        {
            qDebug() << "状态: 登录成功";
            // 登录成功时解析URL参数
            QString loginUrl = dataObj["url"].toString();
            if (!loginUrl.isEmpty()) {
                parseLoginUrl(loginUrl);
            }
            break;
        }

        default:
            qDebug() << "状态: 未知状态码" << statusCode;
            break;
        }
    }


}
void BilibiliQRCodePoller::parseLoginUrl(const QString &url)
{
    if (url.isEmpty()) {
        qDebug() << "URL为空，无法解析";
        return;
    }

    qDebug() << "原始URL:" << url;

    // 解析URL
    QUrl parsedUrl(url);

    if (!parsedUrl.isValid()) {
        qDebug() << "URL格式无效";
        return;
    }

    // 获取查询参数
    QUrlQuery query(parsedUrl);

    // 提取登录相关参数
    QString dedeUserID = query.queryItemValue("DedeUserID");
    QString dedeUserIDCkMd5 = query.queryItemValue("DedeUserID__ckMd5");
    QString expires = query.queryItemValue("Expires");
    QString sessdata = query.queryItemValue("SESSDATA");
    QString biliJct = query.queryItemValue("bili_jct");
    QString gourl = query.queryItemValue("gourl");

    qDebug() << "=== 登录参数解析结果 ===";
    qDebug() << "DedeUserID:" << dedeUserID;
    qDebug() << "DedeUserID__ckMd5:" << dedeUserIDCkMd5;
    qDebug() << "Expires:" << expires;
    qDebug() << "SESSDATA:" << sessdata;
    qDebug() << "bili_jct:" << biliJct;
    qDebug() << "gourl:" << QUrl::fromPercentEncoding(gourl.toUtf8()); // 解码URL编码

    // 转换时间戳（如果存在）
    if (!expires.isEmpty()) {
        bool ok;
        qint64 timestamp = expires.toLongLong(&ok);
        if (ok) {
            QDateTime dateTime = QDateTime::fromSecsSinceEpoch(timestamp);
            qDebug() << "过期时间:" << dateTime.toString("yyyy-MM-dd hh:mm:ss");
        }
    }

    qDebug() << "=== 参数解析完成 ===";
}
